<script setup>
import { ref,watch } from 'vue'
import axios from "axios"
import {ElMessage} from 'element-plus'
import router from "@/router/index.js";
import qs from 'qs'
//登录
let dialogLoginVisible = ref(false)
const formLabelWidth = '140px'
let form = ref({
  loginname:'',
  pwd:'',
})
function login() {
  axios({
    url:"http://localhost:8080/login/login",
    method:"post",
    data:form.value
  }).then((response)=>{
    if(response.data===0){
      ElMessage({
        message: '用户名或密码错误',
        type: 'error',
        showClose: true,
      })
    }else if(response.data.rid===1){
      router.push('/main');
      localStorage.setItem('user', JSON.stringify(response.data));
    } else {
      router.push('/user');
        localStorage.setItem('user', JSON.stringify(response.data));
    }
  })
}

//注册
let dialogRegisterVisible = ref(false);
let rform = ref({
  loginname: "",
  pwd: "",
  checkpwd:""
});
const rules = {
  // loginname: [
  //   { required: true, message: '请输入用户名', trigger: 'blur' },
  //   { validator: (rule, value, callback) => {
  //       if (!value ||!/^[a-zA-Z0-9]{1,10}$/.test(value)) {
  //         callback(new Error('用户名只能包含字母和数字，且不大于 10 位'));
  //         isRegisterButtonEnabled.value = false;
  //       } else {
  //         callback();
  //         isRegisterButtonEnabled.value = true;
  //       }
  //     }, trigger: 'blur' }
  // ],
  loginname: [
    { required: true, message: '请输入用户名', trigger: 'blur' },

  ],
  pwd: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { validator: (rule, value, callback) => {
        if (!value || value.length < 6) {
          callback(new Error('密码不能小于 6 位'));
          isRegisterButtonEnabled.value = false;
        } else {
          callback();
          isRegisterButtonEnabled.value = true;
        }
      }, trigger: 'blur' }
  ],
  checkpwd: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { validator: (rule, value, callback) => {
        if (!value || value !== rform.value.pwd) {
          callback(new Error('两次密码不一致'));
          isRegisterButtonEnabled.value = false;
        } else {
          callback();
          isRegisterButtonEnabled.value = true;
        }
      }, trigger: 'blur' }
  ]
};
const isRegisterButtonEnabled=ref(true);
const checkUsernameAvailability=async()=>{
  const loginname=rform.value.loginname;
  if (!loginname ||!/^[a-zA-Z0-9]{1,10}$/.test(loginname)) {
    isRegisterButtonEnabled.value = false;
    return;
  }
  const response=await axios({
    method:"post",
    url:`http://localhost:8080/login/getLoginName`,
    data:{"loginname":loginname},
    transformRequest: [ function(data){
      return qs.stringify(data)  //使用Qs将请求参数序列化
    }],
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'  //必须设置传输方式
    }

  }).then((response)=>{
    if(response.data===0){
      ElMessage({
        message: '用户名已存在',
        type: 'warning',
        showClose: true,
      });
      isRegisterButtonEnabled.value = false;
    }else {
      isRegisterButtonEnabled.value = true;
    }
  })

}
watch([rform.value.loginname, rform.value.pwd, rform.value.checkpwd], async () => {
  let validLoginname = true;
  let validPwd = true;
  let validCheckpwd = true;
  const validateFormItem = (item, rules) => {
    for (const rule of rules) {
      if (rule.required && (!item || item === "")) {
        return false;
      }
      if (rule.validator &&!rule.validator(rule, item)) {
        return false;
      }
    }
    return true;
  };
  validLoginname = validateFormItem(rform.value.loginname, rules.loginname);
  validPwd = validateFormItem(rform.value.pwd, rules.pwd);
  validCheckpwd = validateFormItem(rform.value.checkpwd, rules.checkpwd);
  isRegisterButtonEnabled.value = validLoginname && validPwd && validCheckpwd;
});

const register=async ()=>{
  if(rform.value.checkpwd!=="" && rform.value.pwd!=="" && rform.value.loginname!=="") {
    const response = await axios({
      url: "http://localhost:8080/login/enroll",
      method: "post",
      data: rform.value
    }).then((response) => {
      if (response.data === 1) {
        ElMessage({
          message: '注册成功',
          type: 'success',
          showClose: true,
        })
        dialogRegisterVisible.value=false;
        dialogLoginVisible.value=true;
      } else {
        ElMessage({
          message: '注册失败',
          type: 'error',
          showClose: true,
        })
      }
    })
  }else {
    alert("用户名，密码都不能为空！")
  }
};
</script>


<template>
  <div>
    <el-container>
      <el-header>
        <el-row style="width: 80%">
          <el-col :span="5">
            <img src="../assets/title.png" style="width: 150px;margin-left: 50px">
          </el-col>
          <el-col :span="13">
            <input v-model="input"
                   style="width: 500px;
                          height: 40px;
                          border-bottom-left-radius: 10px;
                          border-top-left-radius: 10px;
                          border:none;
                          margin-top: 25px;
                          "/>
            <el-button
                style="border-bottom-right-radius: 10px;
                       border-top-right-radius: 10px;
                       height: 40px;
                       width: 60px;
                       border:none;
                       background-color: #EFE154;
                       ">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
          </el-col>
          <el-col :span="6">
            <ul class="haeder_ul" style="margin-top: 25px">
              <li><el-button @click="dialogLoginVisible = true"
                             style="background-color: transparent;
                           border:none;
                           color:#ffc400">登录
              </el-button></li>
              <li><el-button @click="dialogRegisterVisible = true"
                             style="background-color: transparent;
                           border:none;
                           color:#ffc400">注册
              </el-button></li>
              <li><el-button @click="dialogLoginVisible = true"
                             style="background-color: transparent;
                           border:none;
                           color:#ffc400">购物车<el-icon><ShoppingCart /></el-icon>
              </el-button></li>
            </ul>
          </el-col>
        </el-row>
      </el-header>

      <el-main class="main">
        <router-view></router-view>
      </el-main>

      <div class="footer">
        <div class="cen">
          <div class="footer-links">
            <ul>
              <li>选购指南</li>
              <li><a href="#">手机</a></li>
              <li><a href="#">电视</a></li>
              <li><a href="#">笔记本</a></li>
              <li><a href="#">平板</a></li>
              <li><a href="#">穿戴</a></li>
              <li><a href="#">耳机</a></li>
              <li><a href="#">家电</a></li>
              <li><a href="#">路由器</a></li>
              <li><a href="#">音箱</a></li>
              <li><a href="#">配件</a></li>
            </ul>
            <ul>
              <li>服务中心</li>
              <li><a href="#">申请售后</a></li>
              <li><a href="#">售后政策</a></li>
              <li><a href="#">维修服务价格</a></li>
              <li><a href="#">订单查询</a></li>
              <li><a href="#">以旧换新</a></li>
              <li><a href="#">保障服务</a></li>
              <li><a href="#">防伪查询</a></li>
              <li><a href="#">F码通道</a></li>
            </ul>
            <ul>
              <li>线下门店</li>
              <li><a href="#">小米之家</a></li>
              <li><a href="#">服务网点</a></li>
              <li><a href="#">授权体验店/专区</a></li>
            </ul>
            <ul>
              <li>关于小米</li>
              <li><a href="#">了解小米</a></li>
              <li><a href="#">加入小米</a></li>
              <li><a href="#">投资有关系</a></li>
              <li><a href="#">可持续发展</a></li>
              <li><a href="#">廉洁举报</a></li>
            </ul>
            <ul>
              <li>关注我们</li>
              <li><a href="#">新浪微博</a></li>
              <li><a href="#">官方微信</a></li>
              <li><a href="#">联系我们</a></li>
              <li><a href="#">公益基金会</a></li>
            </ul>
            <div class="contact">
              <p class="tel">400-100-5678</p>
              <p class="time1">8:00-18:00(仅收市话费)</p>
              <a href="#" class="kefu"><i class="iconfont">&#xe708;</i>人工客服</a>
              <div class="follow">
                <p class="tel">400-180-8888</p>
                <p class="time1">8:00-18:00(仅收市话费)</p>
                <p class="time2">适用于:MIX FOLD、巨屏电视系列</p>
                <a href="#" class="kefu"><i class="iconfont">&#xe708;</i>人工客服</a>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!--      登陆弹框-->
      <el-dialog v-model="dialogLoginVisible" width="500" style="border-radius: 10px">
        <h2 align="center" style="color:#ff9900">欢迎登陆Letgo二手交易平台</h2>
        <el-form :model="form" style="max-width: 400px">
          <el-form-item label="账号" :label-width="formLabelWidth" placeholder="请输入用户名" style="margin-bottom: 40px;margin-top: 30px">
            <el-input v-model="form.loginname" autocomplete="off" />
          </el-form-item>
          <el-form-item label="密码" :label-width="formLabelWidth" placeholder="请输入密码" style="margin-bottom: 30px">
            <el-input v-model="form.pwd" type="password" autocomplete="off" />
          </el-form-item>
        </el-form>
        <template #footer style="display: flex;justify-content: center;">
          <div class="dialog-footer" style="width: 80%">
            <div>
              <a href="#" style="margin-right: 5px">忘记账号</a>
              <a href="#">忘记密码</a>
            </div>
            <el-button @click="login"
                       style="width: 100px;
                              background-color: #EFE154;
                              margin-bottom: 30px;
                              margin-right: 30px"
            >登录
            </el-button>
          </div>
        </template>
      </el-dialog>

      <!--      注册弹框-->
      <el-dialog v-model="dialogRegisterVisible" width="500" style="border-radius: 10px">
        <h2 align="center" style="color:#ffc400">注册</h2>
        <el-form :model="rform" :rules="rules" ref="formRef" style="max-width: 400px" >
          <el-form-item label="账号" :label-width="formLabelWidth" style="margin-bottom: 30px;margin-top: 30px">
            <el-input v-model="rform.loginname" placeholder="请输入用户名" autocomplete="off" @blur="checkUsernameAvailability" />
          </el-form-item>
          <el-form-item prop="pwd"  label="密码" :label-width="formLabelWidth" style="margin-bottom: 30px">
            <el-input v-model="rform.pwd" type="password" placeholder="请输入密码" autocomplete="off" />
          </el-form-item>
          <el-form-item prop="checkpwd"  label="确认密码" :label-width="formLabelWidth" style="margin-bottom: 30px">
            <el-input v-model="rform.checkpwd" placeholder="请再次输入密码" type="password" autocomplete="off" />
          </el-form-item>
        </el-form>
        <template #footer style="display: flex;justify-content: center;">
          <div class="dialog-footer">
            <el-button :disabled="!isRegisterButtonEnabled" @click="register"
                       style="width: 100px;
                              background-color: #EFE154;
                              margin-bottom: 30px;
                              margin-right: 30px"
            >注册
            </el-button>
          </div>
        </template>
      </el-dialog>

    </el-container>
  </div>
</template>

<style scoped>
/* 在线链接服务仅供平台体验和调试使用，平台不承诺服务的稳定性，企业客户需下载字体包自行发布使用并做好备份。 */
@font-face {
  font-family: 'iconfont';  /* Project id 4674015 */
  src: url('https://at.alicdn.com/t/c/font_4674015_ifd94q3kz5.woff2?t=1730634819589') format('woff2'),
  url('https://at.alicdn.com/t/c/font_4674015_ifd94q3kz5.woff?t=1730634819589') format('woff'),
  url('https://at.alicdn.com/t/c/font_4674015_ifd94q3kz5.ttf?t=1730634819589') format('truetype');
}
.iconfont{
  font-family:"iconfont" !important;
  font-size:16px;font-style:normal;
  -webkit-font-smoothing: antialiased;
  -webkit-text-stroke-width: 0.2px;
  -moz-osx-font-smoothing: grayscale;}

.el-header{
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100px;
  background-color: #3b3a3a;
}
.haeder_ul>li{
  float:left;
  margin-right: 5px;
}
.main {
  width: 100%;
//height: 200px;
  background-color: #f5f5f5;
}
/* footer */
.footer{
  width: 100%;
  height: 400px;
}
.footer .cen{
  width: 1226px;
  margin: 0 auto;
}

.footer-links {
  width: 100%;
//height: 112px;
  padding: 30px 30px;
//background-color: #54efdd;
}
.footer-links ul {
  float: left;
  width: 160px;
  text-align: center;
}

.footer-links a {
  color: #757575;
  font-size: 12px;
}

.footer-links a:hover {
  color: #ff6700;
}

.footer-links li:first-child {
  color: #424242;
  font-size: 14px;
  height: 17px;
  line-height: 17px;
  margin: -1px 0 26px;
}

.footer-links li {
  height: 18px;
  line-height: 18px;
  margin-top: 10px;
}

.contact {
  width: 251px;
  height: 120px;
  border-left: 1px solid #e0e0e0;
  float: right;
  margin: 0 auto;
}

.tel {
  color: #ff6700;
  font-size: 20px;
  margin-bottom: 5px;
  margin-left: 55px;
}

.time1 {
  color: #616161;
  font-size: 12px;
  margin-bottom: 5px;
  margin-left: 55px;
}

.time2 {
  margin-left: 55px;
}

.footer-links .kefu {
  width: 120px;
  height: 30px;
  margin: 0 auto;
  line-height: 28px;
  border: 1px solid #ff6700;
  display: block;
  box-sizing: border-box;
  color: #ff6700;
  transition: all .4s;
}
.kefu i {
  margin-left: 25px;
  font-size: 11px;
}

.footer-links .kefu:hover {
  background-color: #f25807;
  border-color: #f25807;
  color: #fff;
}
</style>